#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "circle_queue.hpp"

// 基于共享内存的循环队列

int main()
{
    // 初始化共享内存
    int shmid = shmget(0x5005, sizeof(CircleQueue<int, 5>), 0640|IPC_CREAT);
    if (shmid == -1)
    {
        std::cout << "shmget(0x5005) failed" << std::endl;
        return -1;
    }
    
    // 把共享内存链接到当前进程的地址空间
    CircleQueue<int, 5> *q = (CircleQueue<int, 5> *)shmat(shmid, 0, 0);
    if (q == (void *)-1)
    {
        std::cout << "shmat() failed" << std::endl;
        return -1;
    }
    
    // 初始化循环队列
    q->init();

    int elem;
    elem = 1;
    q->push(elem);
    elem = 2;
    q->push(elem);
    elem = 3;
    q->push(elem);
    std::cout << "队列的长度:" << q->size() << std::endl;
    q->print_queue();

    elem = q->head();
    q->pop();
    std::cout << "出队元素值:" << elem << std::endl;
    elem = q->head();
    q->pop();
    std::cout << "出队元素值:" << elem << std::endl;

    elem = 11;
    q->push(elem);
    elem = 12;
    q->push(elem);
    elem = 13;
    q->push(elem);
    elem = 14;
    q->push(elem);
    elem = 15;
    q->push(elem);
    std::cout << "队列的长度:" << q->size() << std::endl;
    q->print_queue();

    // 把共享内存从当前进程中分离
    shmdt(q);  
}

